<template>
  <div class="question-type">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="题目">
        <el-input v-model="queryParams.content" placeholder="请输入题目"
          clearable size="small" style="width: 180px"/>
      </el-form-item>
      <el-form-item label="试题类型">
        <el-select v-model="queryParams.type" clearable size="small"  placeholder="请选择">
          <el-option v-for="item in typeOptions" :key="item.dictValue"
            :label="item.dictLabel" :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="试题类别">
        <el-select v-model="queryParams.category" clearable size="small"  placeholder="请选择">
          <el-option v-for="item in categoryOptions" :key="item.dictValue"
            :label="item.dictLabel" :value="item.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBatch()"
          :disabled="multiple">删除</el-button>
      </el-col>
    </el-row>

    <el-table :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="80"/>
      <el-table-column label="题目" align="center" prop="content" :show-overflow-tooltip="true"/>
      <el-table-column label="题目类型" align="center" prop="type" :formatter="typeFormat"/>
      <el-table-column label="题目类别" align="center" prop="category" :formatter="categoryFormat"/>
      <el-table-column label="正确答案" align="center" prop="answer"/>
<!--      <el-table-column label="题目分数" align="center" prop="score"/>-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="170"/>
<!--      <el-table-column label="修改时间" align="center" prop="modifyTime" width="170"/>-->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope" >
          <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
            <el-button size="mini" circle type="success" icon="el-icon-edit" @click="handleEdit(scope.row)"/>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
            <el-button size="mini" circle type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total"
      :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList"/>


    <el-dialog title="试题编辑" :visible.sync="dialogVisible" width="70%">
      <el-divider content-position="left" >编辑试题</el-divider>
      <el-form ref="formRef"  :rules="rules" :model="objectData" label-width="80px">
        <div class="header-dev" >
          <el-form-item :inline="true" label="试题类型"  prop="type" >
            <template>
              <el-radio-group v-model="objectData.type" @input="clickInput"  size="small">
              <el-radio :label="1" name="type" :disabled="redact === false ? true : false"  size="medium" border>单选题</el-radio>
              <el-radio :label="2" name="type" :disabled="redact === false ? true : false"  size="medium" border>多选题</el-radio>
              <el-radio :label="3" name="type" :disabled="redact === false ? true : false"  size="medium" border>判断题</el-radio>
              <el-radio :label="4" name="type" :disabled="redact === false ? true : false"  size="medium" border>填空题</el-radio>
              <el-radio :label="5" name="type" :disabled="redact === false ? true : false"  size="medium" border>简答题</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
          <el-form-item label="试题类别" prop="category">
            <el-select  v-model="objectData.category" placeholder="请选择试题类别">
              <el-option v-for="item in categoryOptions" :key="item.dictValue" :value="item.dictValue" :label="item.dictLabel"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-divider content-position="left">编写题目</el-divider>
        <el-form-item label="题目"   prop="content">
          <el-input type="textarea" style="width: 80%;" v-model="objectData.content"></el-input>
        </el-form-item>
        <div v-if="objectData.type === 1 || objectData.type === 2 || objectData.type === 3 ">
          <el-form-item label="答题选项" style="width: 90%;" >
            <template v-for="(item,index) in choice">
              <div  style="display: flex; align-items: flex-start; gap: 50px; ">
                <el-tag>{{item.tag}}</el-tag>
                <div style="border: 1px solid #ccc; flex: 1;width: 100px">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editors[index].editor"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                  />
                  <Editor
                    style="height: 130px; overflow-y: hidden;"
                    v-model="item.option"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="(editor) => onCreated(editor, index)"
                  />
                </div>
              </div>
            </template>
          </el-form-item>
        </div>

        <!--      答案-->
        <div>
            <div v-if="objectData.type === 1">
              <el-form-item label="答案" prop="answer">
              <el-radio-group v-model="objectData.answer">
                <el-radio label="A">A</el-radio>
                <el-radio label="B">B</el-radio>
                <el-radio label="C">C</el-radio>
                <el-radio label="D">D</el-radio>
              </el-radio-group>
              </el-form-item>
            </div>
            <div v-if="objectData.type === 2">
              <el-form-item label="答案" prop="answerTow">
                <el-checkbox-group v-model="checkList">
                  <el-checkbox label="A">A</el-checkbox>
                  <el-checkbox label="B">B</el-checkbox>
                  <el-checkbox label="C">C</el-checkbox>
                  <el-checkbox label="D">D</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
            <div v-if="objectData.type === 3">
              <el-form-item label="答案" prop="answer">
              <el-radio-group v-model="objectData.answer">
                <el-radio label="A" >A</el-radio>
                <el-radio label="B"  >B</el-radio>
              </el-radio-group>
              </el-form-item>
            </div>
            <div v-if="objectData.type === 4">
              <el-form-item label="答案" prop="answer">
              <el-input type="textarea" style="width: 80%;" v-model="objectData.answer"></el-input>
              </el-form-item>
            </div>
<!--            <div v-if="objectData.type === 5">-->
<!--              <el-input type="textarea" style="width: 80%;" v-model="objectData.answer"></el-input>-->
<!--            </div>-->

        </div>
<!--        <el-form-item label="题目分数" prop="score" >-->
<!--          <el-input-number v-model="objectData.score"  :min="1" :max="100" label="描述文字"></el-input-number>-->
<!--        </el-form-item>-->
        <el-form-item label="解析"  >
          <el-input type="textarea" style="width: 80%;" v-model="objectData.analysis"></el-input>
        </el-form-item>

      </el-form>



      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submit">确 定</el-button>
  </span>
    </el-dialog>



  </div>

</template>

<style src="@wangeditor/editor/dist/css/style.css"></style>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {
  addQuestions, deleteQuestions, delListQuestions, detailDictionary, getDetail, pageList, updateQuestions
} from "@/api/regulatory/questions";

export default {
  components: { Editor, Toolbar }, // 注册组件
  data() {
    return {
      redact: true,
      rules: {
        type: [
          {required: true, message: '请选择题目类型', trigger: 'change'}
        ],
        category: [
          {required: true, message: '请选择题目类别', trigger: 'change'}
        ],
        content: [
          {required: true, message: '请输入题目', trigger: 'blur'}
        ],
        answer: [
          {required: true, message: '请输入答案', trigger: 'blur'}
        ],
      },
      checkList: [],//多选题框选中
      rowList: [], // 表格多选按钮选中行
      questionList:[],//列表数据
      typeOptions:[], //题目类型下拉
      categoryOptions:[], //题目类别下拉
      // 查询参数
      total:0,//总条数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type:undefined,
        content:undefined,
        category : undefined
      },
      dialogVisible: false,
      editor: null,
      toolbarConfig: { },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
      questionType: 'single',
      jsonData: null,
      choice:[//单多选答题选项
        { option:'',tag:'A'},
        { option:'',tag:'B'},
        // { option:'',tag:'C'},
        // { option:'',tag:'D'},
      ],
      editors:[ // 存放编辑器实例
        {editor:null},
        {editor:null},
        {editor:null},
        {editor:null},
      ],
      multiple: true, // 多选按钮
      addDel : 1, // 1新增 2删除
      contentList:[],
      objectData:{
        type: 1,//题型
        category: '',//试题分类
        content:'',//题目
        option: '',//选项
        answer: 'A',//答案
        analysis:'',//题目解析
      }
    }
  },
  created() {
    //题目类型下拉框赋值
    this.getDicts("questions_type").then(response => {
      this.typeOptions = response.data;
    })
    //题目类别下拉框赋值
    this.getDicts("questions_category").then(response => {
      this.categoryOptions = response.data;
    })
    //列表查询
    this.getList()
  },
  methods: {
    clickInput(value){
     if (this.objectData.type ===3){
       this.choice=[
         { option:'对',tag:'A'},
         { option:'错',tag:'B'},
       ]
     }else {
       this.choice=[
         { option:'',tag:'A'},
         { option:'',tag:'B'},
         { option:'',tag:'C'},
         { option:'',tag:'D'},
       ]
     }
    },
    //清除表单验证
    formClose() {
      // 等待DOM更新后重置表单
      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.resetFields()
          this.$refs.formRef.clearValidate()
        }
        // 清空编辑器内容
        if (this.editor) {
          this.editor.setHtml('')
        }
      })
    },
    //重置按钮
    resetQuery(){
      this.queryParams ={
        type:undefined,
        content:undefined,
        category:undefined
      }
      this.queryParams.pageNum = 1
      this.getList();
    },
    //获取列表
    getList(){
      pageList(this.queryParams).then((response) => {
        this.questionList = response.data.records;
        this.total = response.data.total;
      });
    },
    /** 题目类型字典回显处理 */
    typeFormat(row) {
      return this.selectDictLabel(this.typeOptions,row.type)
    },
    /** 题目类别字典回显处理 */
    categoryFormat(row) {
      return this.selectDictLabel(this.categoryOptions,row.category)
    },
    //多选框选中获取
    handleSelectionChange(selection) {
      this.rowList = selection.map(item => Number(item.id))
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 编辑显示
    handleEdit(row) {
      this.redact = false
      this.formClose()

      getDetail(row).then((response) => {
        this.objectData = response.data
        this.objectData.category = String(this.objectData.category)
        this.choice = JSON.parse(response.data.option);
        this.addDel = 2
      }).finally(() =>{
        if (this.objectData.type === 2) {
          this.checkList = this.objectData.answer.split(',')
        }
      })

      this.dialogVisible = true

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm("是否确认删除数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() =>{
        deleteQuestions(row).then((response) => {
          this.getList();
          this.msgSuccess("删除成功");
        });
      })
    },
    // 批量删除
    handleDeleteBatch() {
      this.$confirm("是否确认删除选择的数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delListQuestions(this.rowList).then((resp) => {
            this.getList();
            this.msgSuccess("删除成功");
          });
        })
        .catch(function () {});
    },
    //添加显示弹窗
    handleAdd(){
      this.redact = true
      this.formClose()
      this.checkList = []
      this.addDel = 1
      this.reset()
      this.dialogVisible = true
    },
    handleQuery() {//收索按钮
      this.queryParams.pageNum = 1;
      this.getList();
    },
    submit(){
      this.$refs.formRef.validate((valid) => {
        if (valid) {

      //添加单选
      if((this.objectData.type === 1 ||this.objectData.type === 3 ) && this.addDel === 1){
        this.objectData.option =JSON.stringify(this.choice)
          addQuestions(this.objectData).then(res =>{
            this.getList()
            this.msgSuccess("提交成功");
            this.reset()
          })
      }
      if(this.objectData.type === 2 && this.addDel === 1){
        this.objectData.answer = this.checkList.join(',')

        this.objectData.option =JSON.stringify(this.choice)
        addQuestions(this.objectData).then(res =>{
          this.getList()
          this.msgSuccess("提交成功");
          this.reset()
        })
      }
      if(( this.objectData.type === 4 || this.objectData.type === 5) && this.addDel === 1){
        addQuestions(this.objectData).then(res => {
          this.getList()
          this.msgSuccess("提交成功");
          this.reset()
        })
      }
      //修改单选
      if((this.objectData.type === 1||this.objectData.type === 2||this.objectData.type === 3) && this.addDel === 2){
        this.objectData.option =JSON.stringify(this.choice)
        if(this.objectData.type === 2){
          this.objectData.answer = this.checkList.join(',')
        }
        updateQuestions(this.objectData).then(res =>{
          this.getList()
          this.msgSuccess("修改成功");
        });
      }
          if((this.objectData.type === 4 || this.objectData.type === 5) && this.addDel === 2){
            updateQuestions(this.objectData).then(res =>{
              this.getList()
              this.msgSuccess("修改成功");
            });
          }
      this.dialogVisible = false;
        }
      });
    },
    reset(){
      this.objectData = {
        content:undefined,//标题
        type: 1,//题型
        category : '', //分类
        option: undefined,//选项
        answer:undefined,//答案
        analysis:undefined,//题目解析
      }
      this.choice = [//单多选答题选项
        { option:'',tag:'A'},
        { option:'',tag:'B'},
        { option:'',tag:'C'},
        { option:'',tag:'D'},
      ]
    },
      onCreated(editor,index ) {
      this.editors[index].editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
  }
}
</script>

<style scoped>
.question-type{
  padding: 20px;
}
</style>
